package com.example.mvitest.mvi

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mvitest.R
import com.example.mvitest.activityRepeatOnLifecycle
import com.example.mvitest.databinding.ActivityMainBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    private val viewModel by viewModels<MviViewModel>()

    private lateinit var binding: ActivityMainBinding
    private lateinit var myAdapter: MyAdapter
    private var list = mutableListOf<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initView()
        initObserver()
        viewModel.handleData(ActionView.LoadData)
    }

    private fun initView() {
        myAdapter = MyAdapter(list)
        binding.recyclerView.run {
            layoutManager = LinearLayoutManager(this@MainActivity).also {
                it.orientation = LinearLayoutManager.VERTICAL
            }
            this.adapter = myAdapter
        }

        binding.btRefresh.setOnClickListener {
            viewModel.handleData(ActionView.OnRefresh)
        }

        myAdapter.setOnItemClick {
            viewModel.handleData(ActionView.ItemClick(list[it]))
        }

    }


    private fun initObserver() {
        //状态监听
        viewModel.statusLiveData.observe(this) {
            when(it.status){
                ActionStatus.LoadingInit->{
                    binding.llProgress.visibility = View.VISIBLE
                    binding.tvProgressState.text = "加载中..."
                }
                ActionStatus.LoadingFinish->{
                    binding.llProgress.visibility = View.GONE
                }
                ActionStatus.LoadingSuccess->{
                    binding.llProgress.visibility = View.GONE
                    list.clear()
                    list.addAll(it.data)
                    myAdapter.notifyDataSetChanged()
                }
            }
        }

        //事件监听
        activityRepeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.eventShareFlow
                .collect {
                when(it){
                    is MviViewEvent.ShowToast->{
                        Toast.makeText(this@MainActivity,it.message,Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

}